package com.yuantu.judiciary.job;

import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wechat.pay.java.service.refund.model.Refund;
import com.yuantu.judiciary.common.SysOnOffState;
import com.yuantu.judiciary.dao.*;
import com.yuantu.judiciary.model.api.*;
import com.yuantu.judiciary.model.domain.*;
import com.yuantu.judiciary.model.dto.*;
import com.yuantu.judiciary.model.enums.*;
import com.yuantu.judiciary.model.vo.CaseTypeNumVO;
import com.yuantu.judiciary.service.IApiAliAppletService;
import com.yuantu.judiciary.service.IApiWxPayService;
import com.yuantu.judiciary.service.IOpenApiService;
import com.yuantu.judiciary.service.ISmsService;
import com.yuantu.judiciary.utils.Sm2Util;
import com.yuantu.judiciary.utils.StringUtil;
import com.yuantu.judiciary.utils.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 同步认证信息
 *
 * @author syw
 * @since 2023-08-18
 **/
@Component
@Slf4j
public class SyncAuthInfoTask {
    @Resource
    private ISysConfigDao sysConfigDao;
    @Resource
    private ISysOperLogApiDao sysOperLogApiDao;
    @Resource
    private ISysOperLogDao sysOperLogDao;
    @Resource
    private ISmsService smsService;
    @Resource
    private IQueryRecordDao queryRecordDao;
    @Resource
    private IVipOrderRefundDao orderRefundDao;
    @Resource
    private IApiAliAppletService aliAppletService;
    @Resource
    private IApiWxPayService wxPayService;
    @Resource
    private IVipOrderDao orderDao;
    @Resource
    private IVipInfoDao vipInfoDao;
    @Resource
    private IOrgVipRecordDao orgVipRecordDao;
    @Resource
    private IMonitorRecordDao monitorRecordDao;
    @Resource
    private IMonitorEntityDao monitorEntityDao;
    @Resource
    private IOpenApiService openApiService;
    @Resource
    private IAccountDao accountDao;
    @Resource
    private ISmsRecordDao smsRecordDao;


    private static final Gson GSON = new Gson();

    /**
     * 接口调用次数预警
     * 1小时执行一次
     */
    @Scheduled(initialDelay = 30 * 1000, fixedRate = 60 * 60 * 1000)
    public void updateAuthInfo() {
        SysConfigDO config = sysConfigDao.findFirstByTypeAndDeletedFalse(ConfigType.WARNING);
        Boolean verify = !ObjectUtils.isEmpty(config) && SysOnOffState.ON.equals(config.getState());
        if (Boolean.TRUE.equals(verify)) {
            List<SysOperLogApiDO> logs = sysOperLogApiDao.findByCreateTimeAndDeletedFalse(config.getCreateTime(), null);
            if (!CollectionUtils.isEmpty(logs)) {
                int count = Integer.parseInt(config.getRemarks()) - logs.size();
                log.info("接口调用次数预警: 剩余 {} 次", count);
                if (count <= 20) {
//                    log.info("-----发送预警短信-----");
                    List<String> warningPhones = sysConfigDao.getWarningPhones();
//                    log.info("预警手机号列表: {}", JSON.toJSON(warningPhones));
                    if (!CollectionUtils.isEmpty(warningPhones)) {
                        for (String phone : warningPhones) {
//                            log.info("发送预警短信至手机号 {}", phone);
                            smsService.sendWarningCode("20", phone);
                        }
                    }
                }
            }
        }
    }

    @Scheduled(initialDelay = 30 * 1000, fixedRate = 10 * 60 * 1000)
    public void expiredQueryRecord() {
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        Timestamp timestamp48HoursAgo = new Timestamp(currentTime.getTime() - (24 * 60 * 60 * 1000));
        List<QueryRecordDO> aliUnAuthorizedQueryRecords = queryRecordDao.findByTypeAndAuthorizedResultInAndExpiresTimeLessThanAndOriginAndDeletedFalse(
                SearchType.PERSON, Arrays.asList(AuthResultType.SEND_MSG, AuthResultType.AUTHORIZING),
                currentTime, EndpointType.ALIPAY_APPLET
        );
        List<QueryRecordDO> aliExpiredAuthorizeQueryRecords = queryRecordDao.findByTypeAndAuthorizedResultInAndExpiresTimeLessThanAndOriginAndDeletedFalse(
                SearchType.PERSON, Collections.singletonList(AuthResultType.AUTHORIZED_EXPIRED),
                timestamp48HoursAgo, EndpointType.ALIPAY_APPLET
        );
        if (CollectionUtils.isEmpty(aliUnAuthorizedQueryRecords)) {
            log.info("未查到支付宝未授权查询数据");
        } else {
            for (QueryRecordDO unAuthorizedQueryRecord : aliUnAuthorizedQueryRecords) {
                unAuthorizedQueryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED_EXPIRED);
                queryRecordDao.save(unAuthorizedQueryRecord);
            }
        }
        if (CollectionUtils.isEmpty(aliExpiredAuthorizeQueryRecords)) {
            log.info("未查到支付宝授权过期查询数据");
        } else {
            int refundCount = 0;
            int successRefundCount = 0;
            for (QueryRecordDO queryRecord : aliExpiredAuthorizeQueryRecords) {
                if (StringUtils.isNotBlank(queryRecord.getTradeNo()) && !Boolean.TRUE.equals(queryRecord.getSelf())) {
                    VipOrderDO orderInfo = orderDao.findOrderByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
                    if (orderInfo != null && PayState.SUCCESS.equals(orderInfo.getPayState())) {
                       // log.info("查询退单信息，订单号：{}", orderInfo.getTradeNo());
                        VipOrderRefundDO refundInfo = orderRefundDao.findByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
                        //log.info("退单信息查询完毕");
//                        log.info("退款信息：{}", refundInfo == null ? "" : GSON.toJson(refundInfo));
                        if (refundInfo == null) {
                            refundInfo = new VipOrderRefundDO();
                            String refundNo = "RF_" + currentTime.getTime() + "_" + RandomStringUtils.randomNumeric(6);
                            refundInfo.setOrderId(orderInfo.getId());
                            refundInfo.setTradeNo(orderInfo.getTradeNo());
                            refundInfo.setRefundNo(refundNo);
                            refundInfo.setRefundTime(currentTime);
                            refundInfo.setRefundAmount(orderInfo.getTotalPrice());
                            refundInfo.setRefundReason("授权过期");
                            getAliRefundStatus(refundInfo);
                            orderRefundDao.save(refundInfo);
                            changeVipRecord(orderInfo, refundInfo);
                            refundCount++;
                            if ("REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                successRefundCount++;
                            }
                        } else {
                            if (!"REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                getAliRefundStatus(refundInfo);
                                orderRefundDao.save(refundInfo);
                                changeVipRecord(orderInfo, refundInfo);
                                refundCount++;
                                if ("REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                    successRefundCount++;
                                }
                            }
                        }
                    }
                }
            }
            log.info("支付宝端查到过期授权查询数据: {} 条，需处理退款：{} 条，成功退款：{} 条", aliExpiredAuthorizeQueryRecords.size(), refundCount, successRefundCount);
        }

        List<QueryRecordDO> wxUnAuthorizedQueryRecords = queryRecordDao.findByTypeAndAuthorizedResultInAndExpiresTimeLessThanAndOriginAndDeletedFalse(
                SearchType.PERSON, Arrays.asList(AuthResultType.SEND_MSG, AuthResultType.AUTHORIZING),
                currentTime, EndpointType.APPLET
        );
        List<QueryRecordDO> wxExpiredAuthorizeQueryRecords = queryRecordDao.findByTypeAndAuthorizedResultInAndExpiresTimeLessThanAndOriginAndDeletedFalse(
                SearchType.PERSON, Collections.singletonList(AuthResultType.AUTHORIZED_EXPIRED),
                timestamp48HoursAgo, EndpointType.APPLET);

        if (CollectionUtils.isEmpty(wxUnAuthorizedQueryRecords)) {
            log.info("未查到微信未授权查询数据");
        } else {
            for (QueryRecordDO unAuthorizedQueryRecord : wxUnAuthorizedQueryRecords) {
                unAuthorizedQueryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED_EXPIRED);
                queryRecordDao.save(unAuthorizedQueryRecord);
            }
        }

        if (CollectionUtils.isEmpty(wxExpiredAuthorizeQueryRecords)) {
            log.info("未查到微信授权过期查询数据");
        } else {
            int refundCount = 0;
            int successRefundCount = 0;
            for (QueryRecordDO queryRecord : aliExpiredAuthorizeQueryRecords) {
                if (StringUtils.isNotBlank(queryRecord.getTradeNo()) && !Boolean.TRUE.equals(queryRecord.getSelf())) {
                    VipOrderDO orderInfo = orderDao.findOrderByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
                    if (orderInfo != null && PayState.SUCCESS.equals(orderInfo.getPayState())) {
                        Long vipId = orderInfo.getVipId();
                        VipInfoDO vipInfo = vipInfoDao.findByIdAndDeletedFalse(vipId);
                        if (8 != vipInfo.getId()) {
                            continue;
                        }
                       // log.info("查询退单信息，订单号：{}", orderInfo.getTradeNo());
                        VipOrderRefundDO refundInfo = orderRefundDao.findByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
                        //log.info("退单信息查询完毕");
//                        log.info("退款信息：{}", refundInfo == null ? "" : GSON.toJson(refundInfo));
                        if (refundInfo == null) {
                            refundInfo = new VipOrderRefundDO();
                            String refundNo = "RF_" + currentTime.getTime() + "_" + RandomStringUtils.randomNumeric(6);
                            refundInfo.setOrderId(orderInfo.getId());
                            refundInfo.setTradeNo(orderInfo.getTradeNo());
                            refundInfo.setRefundNo(refundNo);
                            refundInfo.setRefundTime(currentTime);
                            refundInfo.setRefundAmount(orderInfo.getTotalPrice());
                            refundInfo.setRefundReason("授权过期");
                            getWxRefundStatus(refundInfo);
                            orderRefundDao.save(refundInfo);
                            changeVipRecord(orderInfo, refundInfo);
                            refundCount++;
                            if ("REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                successRefundCount++;
                            }
                        } else {
                            if (!"REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                getWxRefundStatus(refundInfo);
                                orderRefundDao.save(refundInfo);
                                changeVipRecord(orderInfo, refundInfo);
                                refundCount++;
                                if ("REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
                                    successRefundCount++;
                                }
                            }
                        }
                    }
                }
            }
            log.info("微信端查到过期授权查询数据: {} 条，需处理退款：{} 条，成功退款：{} 条", aliExpiredAuthorizeQueryRecords.size(), refundCount, successRefundCount);
        }
    }

    private void changeVipRecord(VipOrderDO orderInfo, VipOrderRefundDO refundInfo) {
        if ("REFUND_SUCCESS".equals(refundInfo.getRefundStatus())) {
            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(orderInfo.getOrganizationId());
            if (orgVipRecord != null && orgVipRecord.getBuyAlipayAppletSearchTimes() != null && orgVipRecord.getBuyAlipayAppletSearchTimes() > 0) {
                orgVipRecord.setBuyAlipayAppletSearchTimes(orgVipRecord.getBuyAlipayAppletSearchTimes() - 1);
                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() - 1);
                orgVipRecordDao.save(orgVipRecord);
            }
        }
    }

    private void getAliRefundStatus(VipOrderRefundDO res) {
        String refundResponse = aliAppletService.tradeRefund(res.getTradeNo(), res.getRefundAmount().toString(), res.getRefundReason(), res.getRefundNo());
        if (refundResponse == null) {
            res.setRefundStatus("REFUND_FAIL");
            log.info("订单：{} 退款接口失败", res.getTradeNo());
        } else {
            String refundObjectStr = "alipay_trade_refund_response";
            JsonObject refundObject = GSON.fromJson(refundResponse, JsonObject.class);
            if (!refundObject.getAsJsonObject(refundObjectStr).isJsonNull()
                    && "10000".equals(refundObject.getAsJsonObject(refundObjectStr).get("code").getAsString())
                    && "Success".equals(refundObject.getAsJsonObject(refundObjectStr).get("msg").getAsString())
                    && "Y".equals(refundObject.getAsJsonObject(refundObjectStr).get("fund_change").getAsString())
            ) {
                res.setRefundStatus("REFUND_SUCCESS");
                log.info("订单：{} 退款成功", res.getTradeNo());
            } else {
                // 查询退款信息
                String queryRefundResponse = aliAppletService.queryRefund(res.getTradeNo(), res.getRefundNo());
                if (queryRefundResponse == null) {
                    res.setRefundStatus("REFUND_FAIL");
                    log.info("订单：{} 退款查询接口失败", res.getTradeNo());
                } else {
                    String queryRefundObjectStr = "alipay_trade_fastpay_refund_query_response";
                    JsonObject queryRefundObject = GSON.fromJson(queryRefundResponse, JsonObject.class);
                    if (!queryRefundObject.getAsJsonObject(queryRefundObjectStr).isJsonNull()
                            && "10000".equals(queryRefundObject.getAsJsonObject(queryRefundObjectStr).get("code").toString())
                            && "Success".equals(queryRefundObject.getAsJsonObject(queryRefundObjectStr).get("msg").toString())
                            && "REFUND_SUCCESS".equals(queryRefundObject.getAsJsonObject(queryRefundObjectStr).get("refund_status").toString())
                    ) {
                        res.setRefundStatus("REFUND_SUCCESS");
                        log.info("订单：{} 退款成功", res.getTradeNo());
                    } else {
                        res.setRefundStatus("REFUND_FAIL");
                        log.info("订单：{} 退款失败，失败原因：{}", res.getTradeNo(),
                                refundObjectStr + ": " + refundResponse + "\n" + queryRefundObjectStr + ": " + queryRefundResponse
                        );
                    }
                }
            }
        }
    }


    private void getWxRefundStatus(VipOrderRefundDO res) {
        RefundOrderDTO refundOrder = new RefundOrderDTO();
        refundOrder.setRefundNo(res.getRefundNo());
        refundOrder.setTradeNo(res.getTradeNo());
        refundOrder.setTotalPrice(res.getRefundAmount());
        Refund refund = wxPayService.executeRefund(refundOrder);
        if (refund == null) {
            res.setRefundStatus("REFUND_FAIL");
            log.info("订单：{} 退款接口失败", res.getTradeNo());
        } else {
            if ("SUCCESS".equals(refund.getStatus().toString())
            ) {
                res.setRefundStatus("REFUND_SUCCESS");
                log.info("订单：{} 退款成功", res.getTradeNo());
            } else {
                // 查询退款信息
                Refund refundResult = wxPayService.queryRefund(res.getRefundNo());
                if (refundResult == null) {
                    res.setRefundStatus("REFUND_FAIL");
                    log.info("订单：{} 退款查询接口失败", res.getTradeNo());
                } else {

                    if ("SUCCESS".equals(refund.getStatus().toString())
                    ) {
                        res.setRefundStatus("REFUND_SUCCESS");
                        log.info("订单：{} 退款成功", res.getTradeNo());
                    } else {
                        res.setRefundStatus("REFUND_FAIL");
                        log.info("订单：{} 退款失败", res.getTradeNo()
                        );
                    }
                }
            }
        }
    }

    @Scheduled(initialDelay = 30 * 1000, fixedRate = 10 * 60 * 1000)
    public void changeOrderStatusToExpired() {

        LocalDateTime twoHoursAgoLocal = LocalDateTime.now().minusHours(2);
        List<VipOrderDO> unPayOrders = orderDao.findOrderInfosByPayStateAndDeletedFalse(PayState.TO_PAY);
        unPayOrders = unPayOrders.stream().filter(s -> {
            Timestamp createTime = s.getCreateTime();
            LocalDateTime localDateTime = createTime.toLocalDateTime();
            return localDateTime.isBefore(twoHoursAgoLocal);
        }).collect(Collectors.toList());
        log.info("查询出超时订单数：{}", unPayOrders.size());
        for (VipOrderDO unPayOrder : unPayOrders) {
            unPayOrder.setPayState(PayState.EXPIRED);
        }
        orderDao.saveAll(unPayOrders);
    }


    @Scheduled(cron = "0 0 22 1 * ?")
    public void removeOperationLogsOnSchedule() {

        LocalDateTime now = LocalDateTime.now();
        // 减去一个月
        LocalDateTime oneMonthAgo = now.minusMonths(1);
        // 转换回Timestamp
        ZonedDateTime zdt = oneMonthAgo.atZone(ZoneId.systemDefault());
        Timestamp oneMonthAgoTimestamp = Timestamp.from(zdt.toInstant());
        sysOperLogDao.removeByCreateTimeBefore(oneMonthAgoTimestamp);
    }

    @Scheduled(cron = "0 0 21 * * ?")
    public void queryMonitorCaseDetailSchedule() {
        Date now = new Date();
        List<MonitorRecordDO> monitorRecords = monitorRecordDao.findInfosByIsPayTrueAndDisabledFalse();
        monitorRecords = monitorRecords.stream().filter(s -> now.before(s.getExpireTime()) || now.equals(s.getExpireTime())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(monitorRecords)) {
            return;
        }
        MonitorQueryPageDTO monitorQueryPage = new MonitorQueryPageDTO();
        monitorQueryPage.setPageIndex(1);
        monitorQueryPage.setPageSize(1000);
        monitorQueryPage.setQueryDate(now);
        //远程接口查询个人/企业监控案件信息
        List<CaseSimpleDataDTO> monitorPersonInfos = new ArrayList<>();
        try {
            monitorPersonInfos = openApiService.personQueryMonitorProd(monitorQueryPage).getRecords();
        } catch (Exception e) {
            log.info("远程接口查询个人监控案件信息失败，原因：" + e.getMessage(), e);
        }
        List<CaseSimpleDataDTO> monitorEnterInfos = new ArrayList<>();
        try {
            monitorEnterInfos = openApiService.enterQueryMonitorProd(monitorQueryPage).getRecords();
        } catch (Exception e) {
            log.info("远程接口查询企业监控案件信息失败，原因：" + e.getMessage(), e);
        }
        if (CollectionUtils.isEmpty(monitorPersonInfos) && CollectionUtils.isEmpty(monitorEnterInfos)) {
            return;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowStr = dateFormat.format(now);
        for (MonitorRecordDO monitorRecord : monitorRecords) {
            String monitorContent = monitorRecord.getMonitorContent();
            MonitorEntityDO monitorEntity = monitorEntityDao.findInfoByMonitorContentAndMonitorType(monitorContent, monitorRecord.getMonitorType());
            String responseContent = monitorEntity.getResponseContent();
            Date createTime = monitorEntity.getCreateTime();
            String createTimeStr = dateFormat.format(createTime);
            if (StringUtil.isNotBlank(responseContent) && nowStr.equals(createTimeStr)) {
                continue;
            }
            Integer monitorType = monitorRecord.getMonitorType();
            MonitorPersonAddDTO monitorInfo = JSON.parseObject(monitorContent, MonitorPersonAddDTO.class);
            String monitorStr;
            List<CaseSimpleDataDTO> caseSimpleInfos = new ArrayList<>();
            if (MonitorType.PERSON.getValue().equals(monitorType)) {
                monitorStr = monitorInfo.getName() + ":" + monitorInfo.getId();
                for (CaseSimpleDataDTO monitorPersonInfo : monitorPersonInfos) {
                    String name = monitorPersonInfo.getName();
                    if (name.equals(monitorStr)) {
                        caseSimpleInfos.add(monitorPersonInfo);
                    }
                }
            }
            if (MonitorType.ENTER.getValue().equals(monitorType)) {
                monitorStr = monitorInfo.getName();
                for (CaseSimpleDataDTO monitorEnterInfo : monitorEnterInfos) {
                    String name = monitorEnterInfo.getName();
                    if (name.equals(monitorStr)) {
                        caseSimpleInfos.add(monitorEnterInfo);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(caseSimpleInfos)) {
                List<CaseSimpleDTO> caseSimpleList = new ArrayList<>();
                Map<String, List<CaseSimpleDataDTO>> caseSimpleMap = caseSimpleInfos.stream().collect(Collectors.
                        groupingBy(CaseSimpleDataDTO::getCase_type));
                for (String caseType : caseSimpleMap.keySet()) {
                    CaseSimpleDTO caseSimple = new CaseSimpleDTO();
                    List<CaseSimpleDataDTO> caseSimpleDataInfos = caseSimpleMap.get(caseType);
                    caseSimple.setCurrent(caseSimpleDataInfos.size());
                    caseSimple.setRecords(caseSimpleDataInfos);
                    caseSimple.setCaseType(caseType);
                    caseSimpleList.add(caseSimple);
                }
                MonitorCaseDTO monitorCase = new MonitorCaseDTO();
                monitorCase.setName(monitorInfo.getName());
                monitorCase.setCaseInfos(caseSimpleList);
                monitorEntity.setResponseContent(JSON.toJSONString(monitorCase));
                monitorEntity.setCreateTime(now);
                monitorEntityDao.save(monitorEntity);
            }
        }
    }


    @Scheduled(cron = "0 0 7 * * ?")
    public void responseMonitorCaseDetailSchedule() {

        Date now = new Date();
        List<MonitorRecordDO> monitorRecords = monitorRecordDao.findInfosByIsPayTrueAndDisabledFalse();
        monitorRecords = monitorRecords.stream().filter(s -> now.before(s.getExpireTime()) || now.equals(s.getExpireTime())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(monitorRecords)) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);  // 设置当前日期
        calendar.add(Calendar.DAY_OF_MONTH, -1);  // 减去一天
        Date previousDay = calendar.getTime();
        List<Long> accountIds = monitorRecords.stream().map(MonitorRecordDO::getCreatorId).collect(Collectors.toList());
        Map<Long, IAccountDao.AccountUserInfo> accountUserInfoMap = accountDao.getAccountInfo(accountIds).stream().
                collect(Collectors.toMap(IAccountDao.AccountUserInfo::getAccountId, Function.identity()));
        for (MonitorRecordDO monitorRecord : monitorRecords) {
            String monitorContent = monitorRecord.getMonitorContent();
            MonitorEntityDO monitorEntity = monitorEntityDao.findInfoByMonitorContentAndCreateTime(monitorContent, previousDay);
            if (monitorEntity != null) {
                String responseContent = monitorEntity.getResponseContent();
                if (StringUtil.isNotBlank(responseContent)) {
                    MonitorCaseDTO monitorCaseInfo = JSON.parseObject(responseContent, MonitorCaseDTO.class);
                    List<CaseSimpleDTO> caseSimpleInfos = monitorCaseInfo.getCaseInfos();
                    caseSimpleInfos = caseSimpleInfos.stream().filter(s -> s.getCurrent() > 0).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(caseSimpleInfos)) {
                        //发送查看短信
                        String monitorSign = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(monitorContent));
                        String url = "https://admin.njxnet.com/person/#/?monitorSign" + monitorSign;
                        IAccountDao.AccountUserInfo accountUserInfo = accountUserInfoMap.get(monitorRecord.getCreatorId());
                        if (ObjectUtils.isEmpty(accountUserInfo)) {
                            continue;
                        }
                        String phone = accountUserInfo.getPhone();
                        SendTimerQueryDataDTO sendTimerQueryData = new SendTimerQueryDataDTO();
                        List<CaseTypeNumVO> caseTypeNumInfos = new ArrayList<>();
                        List<String> caseTypeInfos = new ArrayList<>();
                        for (CaseSimpleDTO caseSimpleInfo : caseSimpleInfos) {
                            CaseTypeNumVO caseTypeNum = new CaseTypeNumVO();
                            caseTypeNum.setCaseNum(caseSimpleInfo.getCurrent());
                            for (CaseCategory value : CaseCategory.values()) {
                                if (value.getCode().equals(caseSimpleInfo.getCaseType())) {
                                    caseTypeNum.setCaseType(value.getValue());
                                }
                            }
                            caseTypeNumInfos.add(caseTypeNum);
                        }
                        for (CaseTypeNumVO caseTypeNumInfo : caseTypeNumInfos) {
                            String caseTypeInfo = caseTypeNumInfo.getCaseNum() + "条" + caseTypeNumInfo.getCaseType();
                            caseTypeInfos.add(caseTypeInfo);
                        }
                        sendTimerQueryData.setContent(String.join(",", caseTypeInfos));
                        sendTimerQueryData.setName(JSON.parseObject(monitorContent, MonitorPersonAddDTO.class).getName());
                        sendTimerQueryData.setUrl(url);
                        try {
                            smsService.sendTimerMsgCode(phone, null, sendTimerQueryData, SmsTemplateType.TIMER_QUERY);
                            //保存新短信记录
                            SmsRecordDO smsRecord = buildSmsRecordDO(phone, monitorContent,
                                    monitorSign);
                            smsRecordDao.save(smsRecord);
                        } catch (Exception e) {
                            log.info("案件查询短信发送失败，发送人accountId: {}, 手机号：{}", monitorRecord.getCreatorId(), phone, e);
                        }
                    }
                }
            }
        }
    }

    private SmsRecordDO buildSmsRecordDO(String phone, String content, String remarks) {
        SmsRecordDO smsRecord = new SmsRecordDO();
        smsRecord.setPhone(phone);
        smsRecord.setContent(content);
        smsRecord.setType(SmsTemplateType.TIMER_QUERY);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        smsRecord.setCreateTime(currentTime);
        long expiresTime = 86400000L; // 24 * 60 * 60 * 1000 一天
        smsRecord.setExpiresTime(new Timestamp(currentTime.getTime() + expiresTime));
        smsRecord.setRemarks(remarks);
        return smsRecord;
    }


}
